/*
  LICENSE
  -------
Copyright 2005 Nullsoft, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer. 

  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution. 

  * Neither the name of Nullsoft nor the names of its contributors may be used to 
    endorse or promote products derived from this software without specific prior written permission. 
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

//#define MOD_NAME "Trans / Bump"

/*
class C_THISCLASS : public C_RBASE {
	protected:
	public:
		C_THISCLASS();
		float GET_FLOAT(unsigned char *data, var pos);
		void PUT_FLOAT(float f, unsigned char *data, var pos);
		void InitializeStars(var Start);
		void CreateStar(var A);
		virtual ~C_THISCLASS();
		virtual var render(char visdata[2][2][576], var isBeat, var *framebuffer, var *fbout, var w, var h);
		virtual char *get_desc() { return MOD_NAME; }
		virtual HWND conf(HINSTANCE hInstance, HWND hwndParent);
		virtual void load_config(unsigned char *data, var len);
		virtual var  save_config(unsigned char *data);
		var __inline depthof(var c, var i);
    var enabled;
	var depth;
	var depth2;
	var onbeat;
	var durFrames;
	var thisDepth;
	var blend;
	var blendavg;
	var nF;
	var codeHandle;
	var codeHandleBeat;
	var codeHandleInit;
	double *var_x;
	double *var_y;
	double *var_isBeat;
	double *var_isLongBeat;
	double *var_bi;
	RString code1,code2,code3;
	var need_recompile;
	var showlight;
  var initted;
	var invert;
  var AVS_EEL_CONTEXTNAME;
	var oldstyle;
	var buffern;
    CRITICAL_SECTION rcs;
	};


static C_THISCLASS *g_ConfigThis; // global configuration dialog pointer 
static HINSTANCE g_hDllInstance; // global DLL instance pointer (not needed in this example, but could be useful)
*/

var r_bump = function() {
	this.addvar("enabled", 1);
	this.addvar("depth", 30);
	this.addvar("depth2", 100);
	this.addvar("onbeat", 0);
	this.addvar("durframes", 15);
	this.addvar("thisDepth", this.depth);
	this.addvar("blend", 0);
	this.addvar("blendavg", 0);
	this.addvar("nF", 0);
	this.addvar("init_recompile", 1);
	this.addvar("showline", 0);
	this.addvar("initted", 0);
	this.addvar("invert", 0);
	this.addvar("oldstyle", 0);
	this.addvar("buffern", 0);
}

var enabled, depth, depth2, onbeat, durFrames, thisDepth, blend, blendavg, nF, init_recompile, showline, initted, invert, oldstyle, buffern;

var code1 = "x=0.5+cos(t)*0.3;\r\ny=0.5+sin(t)*0.3;\r\nt=t+0.1;";
var code2 = "";
var code3 = "t=0;";

function depthof(var c, var i) {
	var r= max(max((c & 0xFF), ((c & 0xFF00)>>8)), (c & 0xFF0000)>>16);
	return i ? 255 - r : r;
}

function setdepth(var l, var c) {
	var r;
	r=min((c&0xFF)+l, 254);
	r|=min(((c&0xFF00))+(l<<8),254<<8);
	r|=min(((c&0xFF0000))+(l<<16),254<<16);
	return r;
}

function setdepth0(c) {
	var r;
	r=min((c&0xFF), 254);
	r|=min(((c&0xFF00)),254<<8);
	r|=min(((c&0xFF0000)),254<<16);
	return r;
}

// render function
// render should return 0 if it only used framebuffer, or 1 if the new output data is in fbout. this is
// used when you want to do something that you'd otherwise need to make a copy of the framebuffer.
// w and h are the width and height of the screen, in pixels.
// isBeat is 1 if a beat has been detected.
// visdata is in the format of [spectrum:0,wave:1][channel][band].
//#define abs(x) (( x ) >= 0 ? ( x ) : - ( x ))

function r_bump_render(visdata, isBeat, framebuffer, fbout, w, h)
{
	eval(this.getenv());

	var cx,cy;
	var curbuf;

	if (!enabled) return 0;

	/*if (need_recompile) 
	{
		EnterCriticalSection(&rcs);
    
		if (!var_bi || g_reset_vars_on_recompile)
		{
			clearVars();
			var_x = registerVar("x");
			var_y = registerVar("y");
			var_isBeat = registerVar("isbeat");
			var_isLongBeat = registerVar("islbeat");
			var_bi = registerVar("bi");
		 	*var_bi = 1.0;
			initted=0;
		}
		need_recompile=0;
		freeCode(codeHandle);
		freeCode(codeHandleBeat);
		freeCode(codeHandleInit);
		codeHandle = compileCode(code1.get());
		codeHandleBeat = compileCode(code2.get());
		codeHandleInit = compileCode(code3.get());
		LeaveCriticalSection(&rcs);
	}*/
  
	if (isBeat&0x80000000) return 0;

	
	//var *depthbuffer = !buffern ? framebuffer : (var *)getGlobalBuffer(w,h,buffern-1,0);
	var depthbuffer = framebuffer;
	var depthbufferptr = 0;
	var fboutptr = 0;
	var framebufferptr = 0;
	
	if (!depthbuffer) return 0;
	
	curbuf = (depthbuffer==framebuffer);
	
	if (!initted)
	{
		this.init();
		initted=1;
	}

	this.frame();

	if (isBeat)	
		this.beat();

	if (isBeat)
		isBeat=-1;
	else
		isBeat=1;
	if (nF)
		isLongBeat=-1;
	else
		isLongBeat=1;

    
	if (onbeat && isBeat)
	{
		thisDepth=depth2;
		nF = durFrames;
	}
	else if (!nF) thisDepth = depth;
	
	while(i--) fbout[i-1] = 0;
	
	if (oldstyle) {
		cx = floor(x/100.0*w);
		cy = floor(y/100.0*h);
	}
	else
	{
		cx = floor(x*w);
		cy = floor(y*h);
	}
	cx = max(0, min(w, cx));
	cy = max(0, min(h, cy));
	if (showlight) fbout[fboutptr+cx+cy*w]=0xFFFFFF;

	if (var_bi) 
	{
		*var_bi = min(max(*var_bi, 0), 1);
		thisDepth = floor(thisDepth * bi);
	}
	var thisDepth_scaled=(thisDepth<<8)/100;
	depthbufferptr += w+1;
	framebufferptr += w+1;
	fboutptr += w+1;
	var ly=1-cy;
	var i=h-2;
	while (i--)
	{
		var j=w-2;
		var lx=1-cx;
		if (blend)
		{
			while (j--)
			{
				var m1,p1,mw,pw;
				m1=depthbuffer[depthbufferptr+-1];
				p1=depthbuffer[depthbufferptr+1];
				mw=depthbuffer[depthbufferptr+-w];
				pw=depthbuffer[depthbufferptr+w];
				if (!curbuf || (curbuf && (m1||p1||mw||pw)))
				{
					var coul1,coul2;
					coul1=depthof(p1, invert)-depthof(m1, invert)-lx;
					coul2=depthof(pw, invert)-depthof(mw, invert)-ly;
					coul1=127-abs(coul1);
					coul2=127-abs(coul2);
					if (coul1<=0||coul2<=0)
						coul1=setdepth0(framebuffer[framebufferptr+0]);
					else 
						coul1=setdepth((coul1*coul2*thisDepth_scaled)>>(8+6), framebuffer[framebufferptr+0]);
					fbout[fboutptr+0]=BLEND(framebuffer[framebufferptr+0], coul1);
				}
				depthbufferptr++;
				framebufferptr++;
				fboutptr++;
				lx++;
			}
		}
    		else if (blendavg)
    		{
			while (j--)
			{
				var m1,p1,mw,pw;
				m1=depthbuffer[deptbufferptr+-1];
				p1=depthbuffer[depthbufferptr+1];
				mw=depthbuffer[depthbufferptr+-w];
				pw=depthbuffer[depthbuffer+w];
				if (!curbuf || (curbuf && (m1||p1||mw||pw)))
				{
					var coul1,coul2;
					coul1=depthof(p1, invert)-depthof(m1, invert)-lx;
					coul2=depthof(pw, invert)-depthof(mw, invert)-ly;
					coul1=127-abs(coul1);
					coul2=127-abs(coul2);
					if (coul1<=0||coul2<=0)
						coul1=setdepth0(framebuffer[framebufferptr+0]);
					else 
						coul1=setdepth((coul1*coul2*thisDepth_scaled)>>(8+6), framebuffer[framebufferptr+0]);
					fbout[fboutptr+0]=BLEND_AVG(framebuffer[framebufferptr+0], coul1);
				}
				depthbufferptr++;
				framebufferptr++;
				fboutptr++;
				lx++;
			}
		}
		else
		{
			while (j--)
			{
				var m1,p1,mw,pw;
				m1=depthbuffer[depthbufferptr+-1];
				p1=depthbuffer[depthbufferptr+1];
				mw=depthbuffer[depthbufferptr+-w];
				pw=depthbuffer[depthbufferptr+w];
				if (!curbuf || (curbuf && (m1||p1||mw||pw)))
				{
					var coul1,coul2;
					coul1=depthof(p1, invert)-depthof(m1, invert)-lx;
					coul2=depthof(pw, invert)-depthof(mw, invert)-ly;
					coul1=127-abs(coul1);
					coul2=127-abs(coul2);
					if (coul1<=0||coul2<=0)
						coul1=setdepth0(framebuffer[framebufferptr+0]);
					else 
						coul1=setdepth((coul1*coul2*thisDepth_scaled)>>(8+6), framebuffer[framebufferptr+0]);
					fbout[fboutptr+0]=coul1;
				}
				depthbufferptr++;
				framebufferptr++;
			        fboutptr++;
				lx++;
			}
		
		}
		depthbufferptr+=2;
		framebufferptr+=2;
		fboutptr+=2;
		ly++;
	}

	if (nF)
	{
		nF--;
		if (nF)
		{
			var a = abs(depth - depth2) / durFrames;
			thisDepth += a * (depth2 > depth ? -1 : 1);
		
		}
	}

	eval(this.setenv());

	return 1;
}

r_bump.prototype.render = r_bump_render;
r_bump.prototype.addvar = addvar;
r_bump.prototype.setvar = setvar;
r_bump.prototype.getenv = getenv;
r_bump.prototype.setenv = setenv;

/*
        char *text="Bump Light Position\0"
											"How to use the custom light position evaluator:\r\n"
										  " * Init code will be executed each time the window size is changed\r\n"
                      "   or when the effect loads\r\n"
										  " * Frame code is executed before rendering a new frame\r\n"
										  " * Beat code is executed when a beat is detected\r\n"
										  "\r\n"
										  "Predefined variables:\r\n"
										  " x : Light x position, ranges from 0 (left) to 1 (right) (0.5 = center)\r\n"
										  " y : Light y position, ranges from 0 (top) to 1 (bottom) (0.5 = center)\r\n"
										  " isBeat : 1 if no beat, -1 if beat (weird, but old)\r\n"
										  " isLBeat: same as isBeat but persists according to 'shorter/longer' settings\r\n"
										  "          (usable only with OnBeat checked)\r\n"
											" bi:	Bump intensity, ranges	from 0 (flat) to 1 (max specified bump, default)\r\n"
										  " You may also use temporary variables accross code segments\r\n"
										  "\r\n"
										  "Some examples:\r\n"
										  "   Circular move\r\n"
										  "      Init : t=0\r\n"
										  "      Frame: x=0.5+cos(t)*0.3; y=0.5+sin(t)*0.3; t=t+0.1;\r\n"
										  "   Nice motion:\r\n"
										  "      Init : t=0;u=0\r\n"
										  "      Frame: x=0.5+cos(t)*0.3; y=0.5+cos(u)*0.3; t=t+0.1; u=u+0.012;\r\n"
                      ;
*/

